package com.hzlx.config;

import com.hzlx.dao.PermissionDao;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class GatewayConfig {
    @Resource
    PermissionDao permissionDao;
    @Bean(name="definitionLocator") // 避免与Gateway内置的bean同名
    public RouteDefinitionLocator routeDefinitionLocator(){
        return () -> Flux.fromIterable(permissionDao.findAllRoutes().stream()
                .map(perm->{
                    RouteDefinition df = new RouteDefinition();
                    df.setId(perm.getServiceName());
                    df.setUri(URI.create("lb://" + perm.getServiceName()));
                    df.setPredicates(List.of(new PredicateDefinition("Path="+perm.getUri())));
                    return df;
                })
                .collect(Collectors.toList()));
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
